package yzbx.personalwebsite.service;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import yzbx.personalwebsite.config.ConfigData;
import yzbx.personalwebsite.dao.CommonDao;
import yzbx.personalwebsite.entity.*;
import yzbx.personalwebsite.entityWeb.HttpResponse;
import yzbx.personalwebsite.tool.RedisTool;
import yzbx.personalwebsite.tool.utilTool;

import java.util.ArrayList;
import java.util.List;

import static yzbx.personalwebsite.config.Constants.*;
import static yzbx.personalwebsite.tool.RedisTool.REDIS_SAVE_TIME_4H;
import static yzbx.personalwebsite.tool.RedisTool.REDIS_SAVE_TIME_5M;

/**
 * {@code @Author} zxm
 * {@code @Description} 通用的服务
 * {@code @Date} 2024/10/11/16:18
 * {@code @Version} 1.0
 */
@Service
public class CommonService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonService.class);
    // redis工具类
    protected final RedisTool redisTool;
    private final CommonDao commonDao;
    private final ConfigData configData;

    @Autowired
    public CommonService(RedisTool redisTool, CommonDao commonDao, ConfigData configData) {
        this.redisTool = redisTool;
        this.commonDao = commonDao;
        this.configData = configData;
    }

    public HttpResponse sign(@RequestBody() UserEntity user) {
        if (commonDao.selectUserById(user.getId()) == null) {
            user.setLevel(USER_LEVEL_3);
            user.setPassword(utilTool.md5(user.getPassword()));
            commonDao.insertUser(user);
            String sesson = "user_" + utilTool.getRandomId(10);
            List<UserEntity> userList = new ArrayList<>();
            user.setPassword("");
            userList.add(user);
            redisTool.setValue(user.getName(), sesson, userList, REDIS_SAVE_TIME_4H);
            LOGGER.info("用户[{}]注册成功", user.getName());
            return new HttpResponse(HTTP_CODE_200, HTTP_CODE_200_MSG, sesson);
        }
        return new HttpResponse(HTTP_CODE_501, HTTP_CODE_501_MSG, null);
    }

    public HttpResponse login(UserEntity user) {
        UserEntity realUser = commonDao.selectUserById(user.getId());
        if (realUser == null) {
            LOGGER.warn("用户[{}]不存在", user.getId());
            return new HttpResponse(HTTP_CODE_502, HTTP_CODE_502_MSG, null);
        }
        if (!realUser.getPassword().equals(utilTool.md5(user.getPassword()))) {
            LOGGER.warn("用户[{}]密码错误，输入密码[{}],正确密码[{}]", user.getId(), utilTool.md5(user.getPassword()), realUser.getPassword());
            return new HttpResponse(HTTP_CODE_503, HTTP_CODE_503_MSG, null);
        }
        String sesson = "user_" + utilTool.getRandomId(10);
        List<UserEntity> userList = new ArrayList<>();
        realUser.setPassword("");
        userList.add(realUser);
        redisTool.setValue(realUser.getName(), sesson, userList, REDIS_SAVE_TIME_4H);
        LOGGER.info("用户[{}]登录成功", realUser.getName());
        return new HttpResponse(HTTP_CODE_200, HTTP_CODE_200_MSG, sesson);
    }

    public UserEntity getUserInfo(String session) {
        if (session == null || session.isEmpty()) {
            return null;
        }
        List<UserEntity> userList = redisTool.getValue(session, session);
        if (!userList.isEmpty()) {
            redisTool.addSaveTime(session, session, REDIS_SAVE_TIME_4H);
            UserEntity userEntity = JSON.parseObject(JSON.toJSONString(userList.get(0)), UserEntity.class);
            userEntity.setTx(configData.getTxPathLocal() + userEntity.getTx());
            return userEntity;
        }
        return null;
    }

    public void exit(String session) {
        redisTool.delValue(session, session);
    }

    /**
     * 先从redis查询实用网站
     * 查不到再查mysql
     */
    public List<UsefWebsEntity> getUsefWebs() {
        List<UsefWebsEntity> usefWebs = redisTool.getValue(THEME_USEFWEBS, KEY_USEFWEBS);
        if (!usefWebs.isEmpty()) {
            return usefWebs;
        }
        usefWebs = commonDao.selectUsefWebs();
        redisTool.setValue(THEME_USEFWEBS, KEY_USEFWEBS, usefWebs, REDIS_SAVE_TIME_5M);
        return usefWebs;
    }

    /**
     * 新增实用网站，并刷新redis
     */
    public void addUsefWebs(UsefWebsEntity usefWebsEntity) {
        LOGGER.info("新增实用网站数据，网站：{}", usefWebsEntity.getTitle());
        usefWebsEntity.setIsdel("0");
        commonDao.insertUsefWebs(usefWebsEntity);
        List<UsefWebsEntity> usefWebs = commonDao.selectUsefWebs();
        redisTool.setValue(THEME_USEFWEBS, KEY_USEFWEBS, usefWebs, REDIS_SAVE_TIME_5M);
    }

    /**
     * 更新实用网站，并刷新redis
     */
    public void updUsefWebs(UsefWebsEntity usefWebsEntity) {
        LOGGER.info("更新实用网站数据，网站：{}", usefWebsEntity.getTitle());
        commonDao.updateUsefWebs(usefWebsEntity);
        List<UsefWebsEntity> usefWebs = commonDao.selectUsefWebs();
        redisTool.setValue(THEME_USEFWEBS, KEY_USEFWEBS, usefWebs, REDIS_SAVE_TIME_5M);
    }

    /**
     * 逻辑删除网站日志，并刷新redis
     */
    public void delUsefWebs(UsefWebsEntity usefWebsEntity) {
        LOGGER.info("删除实用网站数据，网站：{}", usefWebsEntity.getTitle());
        commonDao.deleteUsefWebs(usefWebsEntity);
        List<UsefWebsEntity> usefWebs = commonDao.selectUsefWebs();
        redisTool.setValue(THEME_USEFWEBS, KEY_USEFWEBS, usefWebs, REDIS_SAVE_TIME_5M);
    }

    /**
     * 先从redis查询网站日志
     * 查不到再查mysql
     */
    public List<WebLogEntity> getWebLog() {
        List<WebLogEntity> weblog = redisTool.getValue(THEME_WEBLOG, KEY_WEBLOG);
        if (!weblog.isEmpty()) {
            return weblog;
        }
        weblog = commonDao.selectWebLog();
        redisTool.setValue(THEME_WEBLOG, KEY_WEBLOG, weblog, REDIS_SAVE_TIME_5M);
        return weblog;
    }

    /**
     * 新增网站日志，并刷新redis
     */
    public void addWebLog(WebLogEntity webLogEntity) {
        LOGGER.info("新增网站日志数据，日志标题：{}", webLogEntity.getTitle());
        webLogEntity.setIsdel("0");
        commonDao.insertWebLog(webLogEntity);
        List<WebLogEntity> weblog = commonDao.selectWebLog();
        redisTool.setValue(THEME_WEBLOG, KEY_WEBLOG, weblog, REDIS_SAVE_TIME_5M);
    }

    /**
     * 逻辑删除网站日志，并刷新redis
     */
    public void delWebLog(WebLogEntity webLogEntity) {
        LOGGER.info("删除网站日志数据，日志标题：{}", webLogEntity.getTitle());
        commonDao.deleteWebLog(webLogEntity);
        List<WebLogEntity> weblog = commonDao.selectWebLog();
        redisTool.setValue(THEME_WEBLOG, KEY_WEBLOG, weblog, REDIS_SAVE_TIME_5M);
    }

    /**
     * 先从redis查询文章
     * 查不到再查mysql
     */
    public List<RecoIdeaEntity> getRecoIdea(String author) {
        List<RecoIdeaEntity> recoIdea = redisTool.getValue(THEME_RECOIDEA + "_" + author, KEY_RECOIDEA + "_" + author);
        if (!recoIdea.isEmpty()) {
            return recoIdea;
        }
        recoIdea = commonDao.selectRecoIdea(author);
        redisTool.setValue(THEME_RECOIDEA + "_" + author, KEY_RECOIDEA + "_" + author, recoIdea, REDIS_SAVE_TIME_5M);
        return recoIdea;
    }

    /**
     * 通过sort查询文章全部信息
     */
    public RecoIdeaEntity getRecoIdeaById(String id, String author) {
        List<RecoIdeaEntity> recoIdeaEntityList = commonDao.selectRecoIdeaById(id, author);
        if (recoIdeaEntityList.isEmpty()) {
            return null;
        }
        return recoIdeaEntityList.get(0);
    }

    /**
     * 新增文章，并刷新redis
     */
    public void addRecoIdea(RecoIdeaEntity recoIdeaEntity) {

        LOGGER.info("新增文章随笔数据，日志标题：{}", recoIdeaEntity.getTitle());
        recoIdeaEntity.setId(utilTool.getRandomId(8));
        recoIdeaEntity.setIsdel("0");
        recoIdeaEntity.setCreateUser(recoIdeaEntity.getAuthor());
        recoIdeaEntity.setCreateTime(utilTool.getNowTime());
        commonDao.insertRecoIdea(recoIdeaEntity);
        String author = recoIdeaEntity.getAuthor();
        List<RecoIdeaEntity> recoIdea = commonDao.selectRecoIdea(author);
        redisTool.setValue(THEME_RECOIDEA + "_" + author, KEY_RECOIDEA + "_" + author, recoIdea, REDIS_SAVE_TIME_5M);
    }

    /**
     * 逻辑删除文章，并刷新redis
     */
    public void delRecoIdea(RecoIdeaEntity recoIdeaEntity) {
        LOGGER.info("删除文章随笔数据，日志标题：{}", recoIdeaEntity.getTitle());
        commonDao.deleteRecoIdea(recoIdeaEntity);
        String author = recoIdeaEntity.getAuthor();
        List<RecoIdeaEntity> recoIdea = commonDao.selectRecoIdea(author);
        redisTool.setValue(THEME_RECOIDEA + "_" + author, KEY_RECOIDEA + "_" + author, recoIdea, REDIS_SAVE_TIME_5M);
    }

    /**
     * 先从redis查询实用网站组
     * 查不到再查mysql
     */
    public List<UsefWebsGroupEntity> getUsefWebsGroup() {
        List<UsefWebsGroupEntity> usefWebsGroup = redisTool.getValue(THEME_USEFWEBSGROUP, KEY_USEFWEBSGROUP);
        if (!usefWebsGroup.isEmpty()) {
            return usefWebsGroup;
        }
        usefWebsGroup = commonDao.selectUsefWebsGroup();
        redisTool.setValue(THEME_USEFWEBSGROUP, KEY_USEFWEBSGROUP, usefWebsGroup, REDIS_SAVE_TIME_5M);
        return usefWebsGroup;
    }

    /**
     * 新增实用网站组，并刷新redis
     */
    public void addUsefWebsGroup(UsefWebsGroupEntity usefWebsGroupEntity) {

        LOGGER.info("新增实用网站组，网站名称：{}", usefWebsGroupEntity.getName());
        usefWebsGroupEntity.setIsdel("0");
        usefWebsGroupEntity.setCreateTime(utilTool.getNowTime());
        commonDao.insertUsefWebsGroup(usefWebsGroupEntity);
        List<UsefWebsGroupEntity> usefWebsGroup = commonDao.selectUsefWebsGroup();
        redisTool.setValue(THEME_USEFWEBSGROUP, KEY_USEFWEBSGROUP, usefWebsGroup, REDIS_SAVE_TIME_5M);
    }

    /**
     * 逻辑删除实用网站组，原分组变更为未分组，并刷新redis
     */
    public void delUsefWebsGroup(UsefWebsGroupEntity usefWebsGroupEntity) {
        LOGGER.info("删除实用网站组，网站名称：{}", usefWebsGroupEntity.getName());
        usefWebsGroupEntity.setUpdateTime(utilTool.getNowTime());
        commonDao.deleteUsefWebsGroup(usefWebsGroupEntity);
        commonDao.updateUsefWebsGroup(usefWebsGroupEntity.getName());
        List<UsefWebsGroupEntity> usefWebsGroup = commonDao.selectUsefWebsGroup();
        redisTool.setValue(THEME_USEFWEBSGROUP, KEY_USEFWEBSGROUP, usefWebsGroup, REDIS_SAVE_TIME_5M);
        List<UsefWebsEntity> usefWebs = commonDao.selectUsefWebs();
        redisTool.setValue(THEME_USEFWEBS, KEY_USEFWEBS, usefWebs, REDIS_SAVE_TIME_5M);
    }

    /**
     * 获取实用网站访问排行
     */
    public List<UsefWebsUsesVisitRankEntity> getUsefWebsUsesVisitRank() {
        return commonDao.selectUsefWebsUsesVisitRank();
    }

    /**
     * 新增/更新实用网站访问排行
     */
    public void addUsefWebsUsesVisitRank(UsefWebsUsesVisitRankEntity usefWebsUsesVisitRankEntity) {
        List<UsefWebsUsesVisitRankEntity> u = commonDao.selectUsefWebsUsesVisitRankbyTitle(usefWebsUsesVisitRankEntity.getWebTitle());
        if (!u.isEmpty()) {
            commonDao.updateUsefWebsUsesVisitRank(usefWebsUsesVisitRankEntity);
        } else {
            commonDao.insertUsefWebsUsesVisitRank(usefWebsUsesVisitRankEntity);
        }
    }

    /**
     * 新增聊天内容
     */
    public void addTalkRecord(TalkRecordEntity talkRecordEntity) {

        talkRecordEntity.setTime(utilTool.getNowTime("YYYY-MM-dd HH:mm:ss"));
        // 去掉空行
        talkRecordEntity.setText(talkRecordEntity.getText().replaceAll("<p><br></p>", ""));
        talkRecordEntity.setAuthorTx(talkRecordEntity.getAuthorTx().replace(configData.getTxPathLocal(), ""));
        commonDao.insertTalkRecord(talkRecordEntity);
    }

    /**
     * 获取聊天内容
     */
    public List<TalkRecordEntity> getTalkRecord(String talkRoomId) {
        List<TalkRecordEntity> talkRecordEntityList = commonDao.selectTalkRecord(talkRoomId);
        for (TalkRecordEntity te : talkRecordEntityList) {
            te.setAuthorTx(configData.getTxPathLocal() + te.getAuthorTx());
        }
        return talkRecordEntityList;
    }

    /**
     * 获取聊天室
     */
    public List<TalkRoomEntity> getTalkRoom() {
        return commonDao.selectTalkRoom();
    }

}
